@extends('layouts.app')

@section('content')
<!-- 确保 CSRF token 可用于 AJAX 请求 -->
<meta name="csrf-token" content="{{ csrf_token() }}">

<div class="container mt-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1>订单详情</h1>
        <a href="{{ route('backend.orders.index') }}" class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i> 返回订单列表
        </a>
    </div>

    <div class="card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <span>订单编号：{{ $order->order_number }}</span>
            <div>
                <span class="badge {{ match($order->status) {
                    '未支付' => 'bg-warning',
                    '已支付' => 'bg-info', 
                    '已取消' => 'bg-danger',
                    '已退款' => 'bg-secondary',
                    '已处理' => 'bg-primary',
                    '已发货' => 'bg-info',
                    '已签收' => 'bg-success',
                    '申请退货' => 'bg-warning',
                    '退货已发出' => 'bg-secondary',
                    '已完成' => 'bg-success',
                    default => 'bg-secondary'
                } }}">
                    {{ $order->status ?? '未知状态' }}
                </span>
                
                {{-- 商户订单号查询按钮 - 仅在未支付状态时显示 --}}
                @if($order->status == '未支付')
                    <button type="button" 
                            class="btn btn-outline-primary btn-sm ms-2" 
                            id="queryOrderBtn"
                            data-order-number="{{ $order->order_number }}">
                        <i class="fas fa-search"></i> 查询订单状态
                    </button>
                @endif
                @if($order->status == '未支付')
                    <form action="{{ route('backend.orders.updateStatus', $order) }}" method="POST" class="d-inline ml-2">
                        @csrf
                        @method('PUT')
                        <input type="hidden" name="status" value="3">
                        <button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('确定要取消该订单吗？')">
                            取消订单
                        </button>
                    </form>
                @endif
            </div>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <h6 class="text-muted">订单基本信息</h6>
                    <table class="table table-borderless table-sm">
                        <tr>
                            <td><strong>订单ID:</strong></td>
                            <td>{{ $order->id }}</td>
                        </tr>
                        <tr>
                            <td><strong>订单编号:</strong></td>
                            <td>{{ $order->order_number }}</td>
                        </tr>
                        <tr>
                            <td><strong>订单状态:</strong></td>
                            <td>{{ $order->status_name ?? $order->status }}</td>
                        </tr>
                        <tr>
                            <td><strong>订单总价:</strong></td>
                            <td><span class="text-primary fw-bold">¥{{ number_format($order->total_price, 2) }}</span></td>
                        </tr>
                        <tr>
                            <td><strong>创建时间:</strong></td>
                            <td>{{ $order->created_at->format('Y-m-d H:i:s') }}</td>
                        </tr>
                        <tr>
                            <td><strong>更新时间:</strong></td>
                            <td>{{ $order->updated_at->format('Y-m-d H:i:s') }}</td>
                        </tr>
                    </table>
                </div>
                <div class="col-md-6">
                    <h6 class="text-muted">支付信息</h6>
                    <table class="table table-borderless table-sm">
                        @if($order->payment_status)
                        <tr>
                            <td><strong>支付状态:</strong></td>
                            <td>{{ $order->payment_status_name ?? $order->payment_status }}</td>
                        </tr>
                        @endif
                        @if($order->payment_method)
                        <tr>
                            <td><strong>支付方式:</strong></td>
                            <td>{{ $order->payment_method }}</td>
                        </tr>
                        @endif
                        @if($order->transaction_id)
                        <tr>
                            <td><strong>交易号:</strong></td>
                            <td><code>{{ $order->transaction_id }}</code></td>
                        </tr>
                        @endif
                        @if($order->paid_at)
                        <tr>
                            <td><strong>支付时间:</strong></td>
                            <td>{{ $order->paid_at->format('Y-m-d H:i:s') }}</td>
                        </tr>
                        @endif
                        @if($order->subtotal)
                        <tr>
                            <td><strong>商品小计:</strong></td>
                            <td>¥{{ number_format($order->subtotal, 2) }}</td>
                        </tr>
                        @endif
                        @if($order->shipping_fee)
                        <tr>
                            <td><strong>运费:</strong></td>
                            <td>¥{{ number_format($order->shipping_fee, 2) }}</td>
                        </tr>
                        @endif
                        @if($order->discount)
                        <tr>
                            <td><strong>优惠金额:</strong></td>
                            <td>¥{{ number_format($order->discount, 2) }}</td>
                        </tr>
                        @endif
                    </table>
                </div>
            </div>
        </div>
    </div>

    {{-- 查询结果显示区域 --}}
    <div id="queryResultArea" class="card mb-4" style="display: none;">
        <div class="card-header d-flex justify-content-between align-items-center">
            <span>商户订单号查询结果</span>
            <button type="button" class="btn-close" id="closeQueryResult" aria-label="关闭"></button>
        </div>
        <div class="card-body">
            <div id="queryLoading" class="text-center" style="display: none;">
                <div class="spinner-border" role="status">
                    <span class="visually-hidden">查询中...</span>
                </div>
                <p class="mt-2">正在查询订单状态...</p>
            </div>
            <div id="queryContent"></div>
        </div>
    </div>

    <div class="card mb-4">
        <div class="card-header">
            订单商品详情
        </div>
        <div class="card-body">
            <h5 class="card-title">商品列表：</h5>
            @if($order->items && count($order->items) > 0)
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>商品名称</th>
                                <th>商品规格</th>
                                <th>单价</th>
                                <th>数量</th>
                                <th>小计</th>
                                @if($order->items->first()->image)
                                <th>商品图片</th>
                                @endif
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($order->items as $item)
                            <tr>
                                <td>
                                    {{ $item->product_name }}
                                    @if($item->product)
                                        <small class="text-muted d-block">ID: {{ $item->product->id }}</small>
                                    @endif
                                </td>
                                <td>
                                    @if($item->variant_name)
                                        {{ $item->variant_name }}
                                    @else
                                        <span class="text-muted">无规格</span>
                                    @endif
                                </td>
                                <td>¥{{ number_format($item->price, 2) }}</td>
                                <td>{{ $item->quantity }}</td>
                                <td>¥{{ number_format($item->subtotal, 2) }}</td>
                                @if($item->image)
                                <td>
                                    <img src="{{ $item->image_url ?? asset('storage/'.$item->image) }}" 
                                         alt="商品图片" 
                                         class="img-thumbnail" 
                                         style="width: 60px; height: 60px; object-fit: cover;">
                                </td>
                                @endif
                            </tr>
                            @endforeach
                        </tbody>
                        <tfoot>
                            <tr class="table-info">
                                <td colspan="4" class="text-end"><strong>订单总金额：</strong></td>
                                <td><strong>¥{{ number_format($order->total_price, 2) }}</strong></td>
                                @if($order->items->first()->image)
                                <td></td>
                                @endif
                            </tr>
                        </tfoot>
                    </table>
                </div>
            @else
                <div class="alert alert-warning" role="alert">
                    <i class="fas fa-exclamation-triangle"></i> 该订单暂无商品项
                </div>
            @endif
        </div>
    </div>

    <div class="card mb-4">
        <div class="card-header">
            收货人信息
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <h6 class="text-muted">订单中的收货信息</h6>
                    <table class="table table-borderless table-sm">
                        @if($order->receiver_name)
                        <tr>
                            <td><strong>收货人名称：</strong></td>
                            <td>{{ $order->receiver_name }}</td>
                        </tr>
                        @endif
                        @if($order->receiver_phone)
                        <tr>
                            <td><strong>联系电话：</strong></td>
                            <td>{{ $order->receiver_phone }}</td>
                        </tr>
                        @endif
                        @if($order->shipping_address)
                        <tr>
                            <td><strong>收货地址：</strong></td>
                            <td>{{ $order->shipping_address }}</td>
                        </tr>
                        @endif
                    </table>
                </div>
                @if($order->shippingAddress)
                <div class="col-md-6">
                    <h6 class="text-muted">详细收货地址</h6>
                    <table class="table table-borderless table-sm">
                        <tr>
                            <td><strong>收货人：</strong></td>
                            <td>{{ $order->shippingAddress->receiver_name }}</td>
                        </tr>
                        <tr>
                            <td><strong>电话：</strong></td>
                            <td>{{ $order->shippingAddress->receiver_phone }}</td>
                        </tr>
                        <tr>
                            <td><strong>详细地址：</strong></td>
                            <td>{{ $order->shippingAddress->receiver_address }}</td>
                        </tr>
                        @if($order->shippingAddress->created_at)
                        <tr>
                            <td><strong>创建时间：</strong></td>
                            <td>{{ $order->shippingAddress->created_at->format('Y-m-d H:i:s') }}</td>
                        </tr>
                        @endif
                    </table>
                </div>
                <!--@else-->
                <!--<div class="col-md-6">-->
                <!--    <div class="alert alert-info" role="alert">-->
                <!--        <i class="fas fa-info-circle"></i> 未找到详细收货地址信息-->
                <!--    </div>-->
                <!--</div>-->
                <!--@endif-->
            </div>
        </div>
    </div>

    @if($order->status != '已取消')
    <div class="card">
        <div class="card-header">
            物流信息
        </div>
        <div class="card-body">
            @if($order->status == '未支付' || $order->status == '已支付')
                <form action="{{ route('backend.orders.updateStatus', $order) }}" method="POST">
                    @csrf
                    @method('PUT')
                    <input type="hidden" name="status" value="1">
                    
                    <div class="mb-3">
                        <label for="logistics_company" class="form-label">物流公司</label>
                        <input type="text" class="form-control" id="logistics_company" name="logistics_company" 
                               value="{{ $order->logistics_company }}" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="tracking_number" class="form-label">物流单号</label>
                        <input type="text" class="form-control" id="tracking_number" name="tracking_number" 
                               value="{{ $order->tracking_number }}" required>
                    </div>

                    <button type="submit" class="btn btn-primary">确认发货</button>
                </form>
            @else
                <div class="mb-3">
                    <label class="form-label">物流公司</label>
                    <p class="form-control-plaintext">{{ $order->logistics_company ?: '暂无' }}</p>
                </div>
                
                <div class="mb-3">
                    <label class="form-label">物流单号</label>
                    <p class="form-control-plaintext">{{ $order->tracking_number ?: '暂无' }}</p>
                </div>

                @if($order->shipped_at)
                    <p class="card-text">发货时间：{{ $order->shipped_at->format('Y-m-d H:i:s') }}</p>
                @endif
            @endif
        </div>
    </div>
    @endif
</div>

<!-- 引入Bootstrap JS和依赖 -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.3/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

{{-- 商户订单号查询功能 --}}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const queryBtn = document.getElementById('queryOrderBtn');
    const queryResultArea = document.getElementById('queryResultArea');
    const queryLoading = document.getElementById('queryLoading');
    const queryContent = document.getElementById('queryContent');
    const closeBtn = document.getElementById('closeQueryResult');
    
    // 查询按钮点击事件
    if (queryBtn) {
        queryBtn.addEventListener('click', function() {
            const orderNumber = this.getAttribute('data-order-number');
            queryOrderStatus(orderNumber);
        });
    }
    
    // 关闭按钮点击事件
    if (closeBtn) {
        closeBtn.addEventListener('click', function() {
            queryResultArea.style.display = 'none';
        });
    }
    
    // 查询订单状态函数
    function queryOrderStatus(orderNumber) {
        // 显示查询区域和加载状态
        queryResultArea.style.display = 'block';
        queryLoading.style.display = 'block';
        queryContent.innerHTML = '';
        
        // 发送AJAX请求
        fetch(`/api/orders/query/${orderNumber}`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            queryLoading.style.display = 'none';
            
            if (data.success) {
                displayOrderResult(data.order_data, data.timestamp);
            } else {
                displayError(data.message || '查询失败');
            }
        })
        .catch(error => {
            queryLoading.style.display = 'none';
            displayError('网络请求失败，请稍后再试');
            console.error('Error:', error);
        });
    }
    
    // 显示订单结果
    function displayOrderResult(orderData, timestamp) {
        const localOrder = orderData.local_order;
        const wechatQuery = orderData.wechat_pay_query;
        const suggestions = orderData.suggestions || [];
        
        let html = `
            <div class="row">
                <div class="col-md-6">
                    <h6 class="text-muted">本地订单信息</h6>
                    <table class="table table-borderless table-sm">
                        <tr>
                            <td><strong>订单编号：</strong></td>
                            <td>${localOrder.order_number}</td>
                        </tr>
                        <tr>
                            <td><strong>当前状态：</strong></td>
                            <td><span class="badge bg-info">${localOrder.status}</span></td>
                        </tr>
                        <tr>
                            <td><strong>订单金额：</strong></td>
                            <td>¥${parseFloat(localOrder.total_price).toFixed(2)}</td>
                        </tr>
                        <tr>
                            <td><strong>创建时间：</strong></td>
                            <td>${localOrder.created_at}</td>
                        </tr>
                    </table>
                </div>
                <div class="col-md-6">
                    <h6 class="text-muted">微信支付查询结果</h6>`;
        
        if (wechatQuery && wechatQuery.success) {
            const wechatData = wechatQuery.data;
            html += `
                    <table class="table table-borderless table-sm">
                        <tr>
                            <td><strong>支付状态：</strong></td>
                            <td><span class="badge ${getTradeStateBadge(wechatData.trade_state)}">${wechatData.trade_state_desc || wechatData.trade_state}</span></td>
                        </tr>
                        <tr>
                            <td><strong>微信订单号：</strong></td>
                            <td><code>${wechatData.transaction_id || '未生成'}</code></td>
                        </tr>
                        <tr>
                            <td><strong>支付类型：</strong></td>
                            <td>${wechatData.trade_type || '未知'}</td>
                        </tr>
                        <tr>
                            <td><strong>支付银行：</strong></td>
                            <td>${wechatData.bank_type || '未知'}</td>
                        </tr>
                        ${wechatData.success_time ? `
                        <tr>
                            <td><strong>支付时间：</strong></td>
                            <td>${formatWechatTime(wechatData.success_time)}</td>
                        </tr>` : ''}
                        ${wechatData.signature_verified ? `
                        <tr>
                            <td><strong>签名验证：</strong></td>
                            <td><span class="badge bg-success">✓ 已验证</span></td>
                        </tr>` : ''}
                    </table>`;
        } else {
            const errorCode = wechatQuery?.error_code;
            let alertClass = 'alert-warning';
            let icon = 'fas fa-exclamation-triangle';
            
            // 特殊处理签名验证失败
            if (errorCode === 'SIGNATURE_VERIFICATION_FAILED') {
                alertClass = 'alert-danger';
                icon = 'fas fa-shield-alt';
            }
            
            html += `
                    <div class="alert ${alertClass}" role="alert">
                        <i class="${icon}"></i> 
                        ${wechatQuery ? wechatQuery.error_message : '微信支付查询失败'}
                        ${errorCode ? `<br><small>错误代码: ${errorCode}</small>` : ''}
                    </div>`;
        }
        
        html += `
                </div>
            </div>
            <div class="mt-3">
                <small class="text-muted">查询时间：${timestamp}</small>
            </div>`;
        
        // 显示操作建议
        if (suggestions.length > 0) {
            html += `
            <div class="alert alert-info mt-3" role="alert">
                <h6><i class="fas fa-lightbulb"></i> 操作建议：</h6>
                <ul class="mb-0">`;
            suggestions.forEach(suggestion => {
                html += `<li>${suggestion}</li>`;
            });
            html += `
                </ul>
            </div>`;
        }
        
        // 显示同步按钮（仅在微信支付查询成功时显示）
        if (wechatQuery && wechatQuery.success) {
            html += `
            <div class="mt-3">
                <button type="button" 
                        class="btn btn-primary btn-sm" 
                        id="syncStatusBtn"
                        data-order-number="${localOrder.order_number}">
                    <i class="fas fa-sync-alt"></i> 同步订单状态
                </button>
                <small class="text-muted ms-2">点击同步将更新本地订单状态为微信支付的最新状态</small>
            </div>`;
        }
        
        // 成功提示
        html += `
            <div class="alert alert-success mt-3" role="alert">
                <i class="fas fa-check-circle"></i> 查询成功！已获取最新的订单和支付状态信息。
            </div>`;
        
        queryContent.innerHTML = html;
        
        // 为同步按钮添加事件监听器
        const syncBtn = document.getElementById('syncStatusBtn');
        if (syncBtn) {
            syncBtn.addEventListener('click', function() {
                const orderNumber = this.getAttribute('data-order-number');
                syncOrderStatus(orderNumber);
            });
        }
    }
    
    // 显示错误信息
    function displayError(message) {
        const html = `
            <div class="alert alert-danger" role="alert">
                <i class="fas fa-exclamation-triangle"></i> ${message}
            </div>
        `;
        queryContent.innerHTML = html;
    }
    
    // 获取交易状态对应的Bootstrap徽章样式
    function getTradeStateBadge(tradeState) {
        switch(tradeState) {
            case 'SUCCESS': return 'bg-success';
            case 'REFUND': return 'bg-secondary';
            case 'NOTPAY': return 'bg-warning';
            case 'CLOSED': return 'bg-danger';
            case 'REVOKED': return 'bg-danger';
            case 'USERPAYING': return 'bg-info';
            case 'PAYERROR': return 'bg-danger';
            default: return 'bg-secondary';
        }
    }
    
    // 格式化微信时间
    function formatWechatTime(timeStr) {
        if (!timeStr) return '未知';
        try {
            // 微信时间格式：2018-06-08T10:34:56+08:00
            const date = new Date(timeStr);
            return date.toLocaleString('zh-CN');
        } catch (e) {
            return timeStr;
        }
    }
    
    // 同步订单状态函数
    function syncOrderStatus(orderNumber) {
        const syncBtn = document.getElementById('syncStatusBtn');
        
        // 禁用按钮并显示加载状态
        if (syncBtn) {
            syncBtn.disabled = true;
            syncBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 同步中...';
        }
        
        // 发送同步请求
        fetch(`/api/orders/sync-wechat-status/${orderNumber}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            // 恢复按钮状态
            if (syncBtn) {
                syncBtn.disabled = false;
                syncBtn.innerHTML = '<i class="fas fa-sync-alt"></i> 同步订单状态';
            }
            
            if (data.success) {
                displaySyncSuccess(data);
                // 3秒后自动刷新页面以显示最新状态
                setTimeout(() => {
                    window.location.reload();
                }, 3000);
            } else {
                displaySyncError(data.message || '同步失败');
            }
        })
        .catch(error => {
            // 恢复按钮状态
            if (syncBtn) {
                syncBtn.disabled = false;
                syncBtn.innerHTML = '<i class="fas fa-sync-alt"></i> 同步订单状态';
            }
            
            displaySyncError('网络请求失败，请稍后再试');
            console.error('Sync Error:', error);
        });
    }
    
    // 显示同步成功的结果
    function displaySyncSuccess(data) {
        const orderData = data.order_data;
        const successHtml = `
            <div class="alert alert-success mt-3" role="alert">
                <h6><i class="fas fa-check-circle"></i> 订单状态同步成功！</h6>
                <hr>
                <div class="row">
                    <div class="col-md-6">
                        <p class="mb-1"><strong>订单编号：</strong>${orderData.order_number}</p>
                        <p class="mb-1"><strong>原状态：</strong><span class="badge bg-secondary">${orderData.old_status}</span></p>
                        <p class="mb-1"><strong>新状态：</strong><span class="badge bg-success">${orderData.new_status}</span></p>
                    </div>
                    <div class="col-md-6">
                        <p class="mb-1"><strong>微信支付状态：</strong><span class="badge bg-info">${orderData.wechat_trade_state}</span></p>
                        ${orderData.transaction_id ? `<p class="mb-1"><strong>微信订单号：</strong><code>${orderData.transaction_id}</code></p>` : ''}
                        <p class="mb-1"><strong>更新时间：</strong>${orderData.updated_at}</p>
                    </div>
                </div>
                <hr>
                <p class="mb-0"><i class="fas fa-info-circle"></i> 页面将3秒后自动刷新，以显示最新的订单状态。</p>
            </div>
        `;
        
        // 在查询结果区域添加成功信息
        const queryContent = document.getElementById('queryContent');
        if (queryContent) {
            queryContent.insertAdjacentHTML('beforeend', successHtml);
        }
    }
    
    // 显示同步错误信息
    function displaySyncError(message) {
        const errorHtml = `
            <div class="alert alert-danger mt-3" role="alert">
                <h6><i class="fas fa-exclamation-triangle"></i> 订单状态同步失败</h6>
                <hr>
                <p class="mb-0">${message}</p>
            </div>
        `;
        
        // 在查询结果区域添加错误信息
        const queryContent = document.getElementById('queryContent');
        if (queryContent) {
            queryContent.insertAdjacentHTML('beforeend', errorHtml);
        }
    }
});
</script>
@endsection